﻿using System;
using System.Activities;
using System.Linq;
using System.ServiceProcess;
using Reactor.Extensions;
using Reactor.Workflow.Activities;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class StartWindowsService : ReactorCodeActivityBase
    {
        [RequiredArgument]
        public InArgument<ServiceIdentifier> ServiceIdentifier { get; set; }

        #region Overrides of CodeActivity

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            var serviceIdentifier = context.GetValue(ServiceIdentifier);
            var serviceController = ServiceController.GetServices().SingleOrDefault(s => s.ServiceName == serviceIdentifier.ToServiceInstanceString());
            if (serviceController == null) throw new InvalidOperationException(string.Format("WindowsServiceController not found for service: {0}.", serviceIdentifier.ToServiceInstanceString()));

            if (Log.IsDebugEnabled) Log.DebugFormat("Attempting to start service: {0}", serviceController.ServiceName);

            string failureReason;
            if(!serviceController.TryStart(TimeSpan.FromSeconds(30), out failureReason))
                throw new ApplicationException(string.Format("Unable to start windows service: {0}. Reason: {1}", serviceController.ServiceName, failureReason));
        }

        #endregion
    }
}
